package tech.yunland.shop.domain.dao;

import com.moyuer.bsf.domain.dao.BaseDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import tech.yunland.shop.domain.model.GoodsStock;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 文卡<wkwenka@gmail.com>  on 17-3-24.
 */
@Repository
public class GoodsStockDao extends BaseDao<GoodsStock, String> {

    /**
     * 获取可用库存
     *
     * @param goodsIds
     * @param organId
     * @return
     */
    public List<Map<String, Object>>    getUseStock(List<String> goodsIds, String organId, String param, Integer startIndex, Integer rows) {
        param = StringUtils.trimToEmpty(param);

        Map<String, Object> args = new HashMap<>();
        String sql1 = "SELECT\n" +
                "        goods_store.goods_id,\n" +
                "        goods_store.store_num,\n" +
                "        goods_store.state\n" +
                "      FROM goods_store\n" +
                "      WHERE organ_id = :organId AND state = 1";

        String sql2 = "SELECT\n" +
                "        goods_store.goods_id,\n" +
                "        goods_store.store_num*-1,\n" +
                "        goods_store.state\n" +
                "      FROM goods_store\n" +
                "      WHERE organ_id = :organId AND state = 0";
        String sql = "SELECT  goods.name,  result.goods_id,  sum(result.store_num) FROM ";
        sql += "(" + sql1 + " UNION ALL " + sql2 + ") AS result ";
        sql += "LEFT JOIN goods ON result.goods_id = goods.id ";
        sql += "WHERE 1=1 ";
        args.put("organId", organId);

        if (goodsIds != null && goodsIds.size() > 0) {
            if (goodsIds.size() == 1) {
                sql += " AND result.goods_id = :goodIds";
                args.put("goodIds", goodsIds.get(0));
            } else {
                String join = StringUtils.join(goodsIds, "','");
                sql += " AND result.goods_id IN ('" + join + "')";
            }
        }

        if (StringUtils.isNotBlank(param)) {
            sql += " AND (goods.name LIKE :param OR goods.spell LIKE :param)";
            args.put("param", param);
        }

//        sql += " AND goods.kind_code = '10' ";
        sql += " GROUP BY goods.name,goods_id ORDER BY goods.name";

        List<Map<String, Object>> byNamedParamSQL;
        if (startIndex == null || rows == null) {
            byNamedParamSQL = this.findByNamedParamSQL(sql, args);
        } else {
            byNamedParamSQL = this.findByNamedParamSQL(sql, startIndex, rows, args);
        }
        return byNamedParamSQL;

    }
}
